package models

import (
	"github.com/jinzhu/gorm"
	"kop/modules/quest/configuration/dailyquest"
	"kop/modules/quest/entity"
	"kop/pb"
	"kop/util/date"
	"time"
)

func GetDailyQuests(dB *gorm.DB, roleID int32) []*pb.DailyQuest {

	var dailyQuests []entity.DailyQuest
	if err := dB.Where("role_id = ?", roleID).Find(&dailyQuests).Error; err != nil {
		panic(err)
	}

	var result = make([]*pb.DailyQuest, 0, len(dailyQuests))

	for _, q := range dailyQuests {
		var dailyQuest = buildPbDailyQuest(q)
		result = append(result, &dailyQuest)
	}

	// 遍历配置 如果有新的活动就创建
	for _, conf := range dailyquest.Configs {

		var find = false
		for _, dailyQuest := range result {
			if dailyQuest.ID == conf.ID {
				find = true
			}
		}

		if !find {
			var dailyQuest = GetDailyQuest(dB, roleID, conf.ID)
			result = append(result, &dailyQuest)
		}
	}

	return result
}

func GetDailyQuest(dB *gorm.DB, roleID, dailyQuestID int32) pb.DailyQuest {

	var q = entity.DailyQuest{
		RoleID:       roleID,
		DailyQuestID: dailyQuestID,
		Date:         date.Date(time.Now()),
	}

	if err := dB.FirstOrCreate(&q).Error; err != nil {
		panic(err)
	}

	return buildPbDailyQuest(q)
}

func SaveDailyQuest(dB *gorm.DB, dailyQuest *pb.DailyQuest) {

	var q = entity.DailyQuest{
		RoleID:       dailyQuest.RoleID,
		DailyQuestID: dailyQuest.ID,
		Value:        dailyQuest.Value,
		Finish:       dailyQuest.Finish,
		Date:         date.Date(time.Now()),
	}

	if err := dB.Save(&q).Error; err != nil {
		panic(err)
	}

	*dailyQuest = buildPbDailyQuest(q)
}

func buildPbDailyQuest(q entity.DailyQuest) pb.DailyQuest {

	var conf, err = dailyquest.GetByDailyQuestID(q.DailyQuestID)
	if err != nil {
		panic(err)
	}

	var dailyQuest = pb.DailyQuest{
		ID:              q.DailyQuestID,
		RoleID:          q.RoleID,
		Type:            int32(conf.Type),
		Value:           q.Value,
		NeedValue:       conf.NeedValue,
		Finish:          q.Finish,
		DailyQuestValue: conf.DailyQuestValue,
		AwardID:         conf.AwardID,
	}

	if q.Date != date.Date(time.Now()) {
		dailyQuest.Value = 0
		dailyQuest.Finish = false
	}
	return dailyQuest
}
